package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-05-29
 * Time: 22:23
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDao userDao = new UserDao();
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String two_password = req.getParameter("two_password");
        String enteredCaptcha = req.getParameter("captcha");
        HttpSession session = req.getSession();
        String storedCaptcha = (String) session.getAttribute("captcha");

        if (enteredCaptcha != null && enteredCaptcha.equals(storedCaptcha)) {
            // 验证码正确，继续处理登录
            if (username == null || username.isEmpty()) {
                resp.setContentType("text/html; charset=utf8");
                resp.getWriter().write("用户名为空");
                return;
            } else {
                if (password == null || !password.equals(two_password) || password.isEmpty() || two_password.isEmpty()) {
                    resp.setContentType("text/html; charset=utf8");
                    resp.getWriter().write("两次密码不同或有密码为空值");
                    return;
                } else {
                    if (userDao.getUserByName(username) != null) {
                        resp.setContentType("text/html; charset=utf8");
                        resp.getWriter().write("用户名重复");
                    } else {
                        User user = new User();
                        user.setUsername(username);
                        user.setPassword(password);
                        userDao.insert(user);
                        resp.sendRedirect("login.html");
                    }
                }
            }
        } else {
            // 验证码错误
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("验证码有错误");
        }

    }

}
